package com.example.parking.lot;

import com.example.parking.car.Car;
import com.example.parking.ParkingException;
import com.example.parking.Token;

import java.util.List;
import java.util.Optional;

public class ParkingLotGroup {

    private List<? extends ParkingLot> parkingLots;

    public ParkingLotGroup(List<? extends ParkingLot> parkingLots) {
        this.parkingLots = parkingLots;
    }

    public Token park(ParkingLot lot, Car car) throws ParkingException {
        if(!parkingLots.contains(lot)) {
            throw new ParkingException();
        }
        return lot.parkCar(car);
    }

    public boolean isParkingLotGroupAvailable() {
        return !parkingLots.stream()
                .allMatch(parkingLot -> parkingLot.availablePlace() == 0);
    }

    public List<? extends ParkingLot> getParkingLots() {
        return this.parkingLots;
    }

    public Optional<Car> retrieveCar(Token token) throws ParkingException {
        if(!this.parkingLots.contains(token.getParkingLot())){
            throw new ParkingException();
        }

        return token.getParkingLot().retrieveCar(token);
    }

    public void showReport(){
        this.getParkingLots().forEach(ParkingLot::showReport);
    }

    public int retrieveParkingLotCount(){
        return this.getParkingLots().size();
    }

    public int retrieveParkingLotCarCount(){
        return this.getParkingLots().stream().map(ParkingLot::getCarCount).reduce(Integer::sum).orElse(0);
    }
}
